<template>
<div class="wrapper">
  <en-table-layout
    pagination
    :tableData="tableData"
    :height="tableHeight"
    :stripe="false"
    :loading="loading"
    @selection-change="selectionChange">
    <div slot="toolbar" class="inner-toolbar">
      <div class="toolbar-btns">
        <el-button size="mini" type="primary" @click="handleAdd('labelForm')">新增标签</el-button>
        <el-button size="mini" type="primary" @click="handleEnable(0)">启用</el-button>
        <el-button size="mini" type="primary" @click="handleEnable(1)">禁用</el-button>
      </div>
      <div class="toolbar-search">
        <en-table-search
        @search="searchEvent"
        @advancedSearch="advancedSearchEvent"
        advanced
        advancedWidth="520"
        placeholder="请输入标签名">
        <template slot="advanced-content">
          <el-form :model="advancedForm" label-width="100px" ref="advancedForm">
            <el-row>
              <el-col :span="24">
                <el-form-item prop="color" label="标签颜色:">
                  <dg-select v-model="advancedForm.color" dictType="goods_tag_color" placeholder="请选择标签颜色" :defaultValue="advancedForm.color" clearable></dg-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item prop="style" label="标签样式:">
                  <dg-select v-model="advancedForm.style" dictType="goods_tag_style" placeholder="请选择标签样式" :defaultValue="advancedForm.style" clearable></dg-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="显示标签:" prop="goods_tag_display_position">
                  <el-select v-model="advancedForm.goods_tag_display_position" multiple placeholder="请选择显示标签">
                      <el-option label="商品列表" :value="0"></el-option>
                      <el-option label="商品详情" :value="1"></el-option>
                      <el-option label="店铺主页" :value="2"></el-option>
                    </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="24">
                <el-form-item label="有效期间:" prop="times_range"> 
                  <el-date-picker
                    clearable
                    v-model="advancedForm.times_range"
                    type="datetimerange"
                    align="center"
                    :editable="false"
                    unlink-panels
                    range-separator="至"
                    :default-time="['00:00:00', '23:59:59']"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </en-table-search>
    </div>
    </div>
    <template slot="table-columns">
      <el-table-column width="60" type="selection" fixed/>
      <el-table-column prop="status" label="标签状态" min-width="100" >
        <template slot-scope="{ row }">
          {{ row.status == 0 ? '启用' : '禁用' }}
        </template>
      </el-table-column>
      <el-table-column prop="tag_name" label="标签名称" min-width="150" />
      <el-table-column prop="color_name" label="标签颜色" min-width="100" />
      <el-table-column prop="style_name" label="标签样式" min-width="120" />
      <el-table-column prop="type_name" label="标签类型" min-width="120" />
      <el-table-column prop="priority" label="排序" min-width="120" />
      <el-table-column prop="tag_name" label="店铺主页显示" min-width="150" >
        <template slot-scope=" { row } ">
          <span>{{ row.shop_home_page == 0 ? '✔️' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="tag_name" label="商品列表显示" min-width="180" >
        <template slot-scope=" { row } ">
          <span>{{ row.goods_list_page == 0 ? '✔️' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="tag_name" label="商品详情显示" min-width="180" >
        <template slot-scope="{ row }">
          <span>{{ row.goods_details_page == 0 ? '✔️' : '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="有效时间" min-width="280">
        <template slot-scope="{ row }">
          <!-- ( -->
          <span v-if="row.permanent_enable == 0">永久有效</span>
          <span v-else>{{ row.start_time | unixToDate('yyyy-MM-dd hh:mm:ss')}} - {{row.end_time | unixToDate('yyyy-MM-dd hh:mm:ss') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="tag_describe" label="标签描述" min-width="220"/>
      <el-table-column label="操作" fixed="right" min-width="280">
        <template slot-scope="scope">
          <el-button type="primary" @click="addtag(scope.row)">标签商品设置</el-button>
          <el-button type="success" @click="handleEdit(scope.row)" :disabled="scope.row.type !== 1 ? true : false">修改</el-button>
          <el-button type="danger" @click="handleDelete(scope.row)" :disabled="scope.row.type !== 1 ? true : false">删除</el-button>
        </template>
      </el-table-column>
    </template>
    <el-pagination
      slot="pagination"
      v-if="pageData"
      @size-change="handlePageSizeChange"
      @current-change="handlePageCurrentChange"
      :current-page="pageData.page_no"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageData.page_size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageData.data_total">
    </el-pagination>
  </en-table-layout>
    <!-- 批量导入 -->
    <el-dialog :title="title" width="700px" :visible.sync="labelDialog">
      <el-form
        ref="labelForm"
        label-width="85px"
        size="small"
        :model="labelForm"
        :rules="labelFormRules"
        >
        <el-row>
          <el-col :span="24">
            <el-form-item label="标签名称:" prop="tag_name">
              <el-input v-model="labelForm.tag_name" @change="handleInputLength" placeholder="请输入标签名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标签颜色:" prop="color">
              <dg-select v-model="labelForm.color" dictType="goods_tag_color" :defaultValue="labelForm.color" clearable></dg-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签样式:" prop="style">
              <dg-select v-model="labelForm.style" dictType="goods_tag_style" :defaultValue="labelForm.style" clearable></dg-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="15">
            <el-form-item label="显示设置:" prop="goods_tag_display_position">
                <el-checkbox-group v-model="labelForm.goods_tag_display_position" @change="hndlechange(labelForm.goods_tag_display_position)">
                  <el-checkbox label="商品列表"></el-checkbox>
                  <el-checkbox label="商品详情"></el-checkbox>
                  <el-checkbox label="店铺主页"></el-checkbox>
                </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="排序:" prop="priority">
                <el-input-number v-model="labelForm.priority"  :min="1" :max="10000"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="有效期间:" prop="times_range"> 
              <el-date-picker
                :disabled="disabledTime"
                clearable
                v-model="labelForm.times_range"
                type="datetimerange"
                align="center"
                :editable="false"
                unlink-panels
                range-separator="至"
                :default-time="['00:00:00', '23:59:59']"
                start-placeholder="开始时间"
                end-placeholder="结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
              <el-checkbox v-model="labelForm.permanent_enable" @change="handleEffective">永久有效</el-checkbox>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="标签描述:">
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 6}"
                placeholder="请输入内容"
                v-model="labelForm.tag_describe">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary"  @click="submitFileForm('labelForm')" :loading="loading_btn">确 定</el-button>
        <el-button size="small" @click="handleCancel('labelForm')">取 消</el-button>
      </div>
    </el-dialog>
</div>
</template>

<script>
  import * as API_goodsTag from '@/api/goodsTag';
  import dg_select from '@/components/dg-select'
  import { getDictData, filterShowDict } from '@/common/filter-show';
  import { parseTime } from '@/utils/index.js'
  export default {
    name: 'tagManage',
    components: {
      'dg-select': dg_select
    },
    data() {
      return {
        /** 列表loading状态 */
        loading: false,
        loading_btn: false,
        disabledTime: false,
        /** 列表参数 */
        params: {
          page_no: 1,
          page_size: 10
        },
        advancedForm: {
          times_range: [],
          color: undefined,
          style: undefined,
          start_time: undefined,
          end_time: undefined,
          goods_tag_display_position: [],
          shop_home_page: undefined,
          goods_list_page: undefined,
          goods_details_page: undefined
        },
        /** 列表数据 */
        tableData: [],
        /** 列表分页数据 */
        pageData: [],
        /** 多选 */
        multipleChoice: [],
        // 新增标签弹框
        labelDialog: false,
        title: '新增',
        // 新增标签表单
        labelForm: {
          tag_id: undefined,
          tag_name: undefined,
          permanent_enable: false,
          priority: 1,
          color: undefined,
          style: undefined,
          start_time: undefined,
          end_time: undefined,
          goods_tag_display_position: [],
          times_range: [],
          tag_describe: undefined
        },
        labelFormRules: {
          tag_name: [
            {
              required: true,
              trigger: 'blur',
              message: '标签名称不能为空'
            }
          ],
          color: [
            {
              required: true,
              trigger: 'change',
              message: '标签颜色不能为空'
            }
          ],
          style: [
            {
              required: true,
              trigger: 'change',
              message: '标签样式不能为空'
            }
          ],
          goods_tag_display_position: [
            {
              type: 'array', 
              required: true,
              trigger: 'change',
              message: '显示设置最少选择一个'
            }
          ],
          times_range: [
            {
              type: 'array', 
              required: true,
              trigger: 'change',
              message: '截止日期不能为空'
            }
          ]
        }
      }
    },
    filters: {
      // 字典显示转换
      filterDict (_stateVal, _dictType) {
        return filterShowDict(_dictType, _stateVal);
      }
    },
    computed: {
      tableHeight (){
        return document.documentElement.clientHeight - 256 + 'px';
      }
    },
    mounted() {
      // 获取格式化字典数据
      getDictData('goods_tag_color');
      this.GET_TagsList()
    },
    methods: {
      /** 分页大小发生改变 */
      handlePageSizeChange(size) {
        this.params.page_size = size
        this.GET_TagsList()
      },
      /** 分页页数发生改变 */
      handlePageCurrentChange(page) {
        this.params.page_no = page
        this.GET_TagsList()
      },
      /** 标签列表 */
      GET_TagsList() {
        this.loading = true
        API_goodsTag.getTagsList(this.params).then(response => {
          this.loading = false
          this.pageData = {
            page_no: response.page_no,
            page_size: response.page_size,
            data_total: response.data_total
          }
          this.tableData = response.data
        })
      },
      /** 标签商品设置 */
      addtag(row) {
        this.$router.push({ path: `/goods/tag-add/${row.tag_id}`, query: { tag_name: row.tag_name }})
      },
      /**
        * @date 2020/11/24
        * @author kaiqiang
        * @description { 多选 }
      */
      selectionChange(val) {
        this.multipleChoice = val;
      },
      /**
        * @date 2020/11/24
        * @author kaiqiang
        * @description { 新增标签 }
      */
      handleAdd() {
        this.title = "新增";
        this.labelForm = {
          tag_id: undefined,
          tag_name: undefined,
          permanent_enable: false,
          priority: 1,
          color: undefined,
          style: undefined,
          start_time: undefined,
          end_time: undefined,
          goods_tag_display_position: [],
          times_range: [],
          tag_describe: undefined
        }
        this.labelDialog = true;
      },
      /**
        * @date 2020/11/26
        * @author kaiqiang
        * @description { 启用 }
      */
      handleEnable(value) {
        if (!this.multipleChoice.length) {
          this.$message({
            type: 'warning',
            message: '你还没有选择数据哦!'
          })
          return
        }
        let ids = [];
        for (let item of this.multipleChoice) {
          ids.push(item.tag_id)
        }
        let params = {
          'status': value,
          'tag_ids': ids.toString()
        }
        API_goodsTag.deleteTag(params).then(response => {
          this.$message.success("操作成功");
          this.GET_TagsList();
        }).catch((error) => {
          console.log(error)
        })
      },
      /**
        * @date 2020/11/27
        * @author kaiqiang
        * @description { 永久有效的点击事件 }
      */
      handleEffective(val) {
        console.log(val)
        if (val === true) {
          this.disabledTime = true;
          this.labelFormRules.times_range[0].required = false;
          this.labelForm.times_range = [];
          this.labelForm.permanent_enable = true;
        } else {
          this.disabledTime = false;
          this.labelFormRules.times_range[0].required = true;
          this.labelForm.permanent_enable = false;
        }
      },
      /**
        * @date 2020/11/26
        * @author kaiqiang
        * @description { 新增标签确认按钮 }
      */
      submitFileForm(labelForm) {
        this.loading_btn = true;
        this.$refs[labelForm].validate(valide => {
          if (valide) {
            if (this.labelForm.permanent_enable === true) {
              this.labelForm.permanent_enable = 0;
            } else {
              this.labelForm.permanent_enable = 1;
            }
            if (this.labelForm.times_range.length > 0) {
              this.labelForm.start_time = this.labelForm.times_range[0].getTime() / 1000;
              this.labelForm.end_time = this.labelForm.times_range[1].getTime() / 1000;
            }
            API_goodsTag.getAddGoodsTag(this.labelForm).then(response => {
              this.loading_btn = false;
              this.labelDialog = false;
              this.$message.success("操作成功");
              this.$refs[labelForm].resetFields();
              this.GET_TagsList();
            }).catch(error => {
              console.log(error)
              this.loading_btn = false;
              this.$set(this.labelForm, 'times_range', []);
            })
          }
        })
      },
      /**
        * @date 2020/11/26
        * @author kaiqiang
        * @description { 新增标签取消 }
      */
      handleCancel(labelForm) {
        this.labelDialog = false;
        this.loading_btn = false;
        this.$refs[labelForm].resetFields();
      },
      /**
        * @date 2020/11/27
        * @author kaiqiang
        * @description { 修改 }
      */
      handleEdit(row) {
        console.log(typeof( row.permanent_enable ))
        let start_times = new Date(row.start_time * 1000);
        let end_times = new Date(row.end_time * 1000);
        this.labelDialog = true;
        this.title = "修改";
        this.labelForm = {
          tag_id: row.tag_id,
          tag_name: row.tag_name,
          color: row.color + '',
          style: row.style + '',
          priority: row.priority,
          goods_tag_display_position: row.goods_tag_display_position,
          times_range: [start_times, end_times],
          tag_describe: row.tag_describe
        }
        if (row.permanent_enable === 0) {
          this.disabledTime = true;
          this.labelFormRules.times_range[0].required = false;
          this.labelForm.times_range = [];
          this.labelForm.permanent_enable = true;
          console.log(this.labelForm.permanent_enable)
        } else {
          this.labelForm.permanent_enable = false;
        }
      },
      hndlechange(val) {
        this.labelForm.goods_tag_display_position = val;
      },
      /**
        * @date 2020/11/28
        * @author kaiqiang
        * @description { 删除 }
      */
      handleDelete(row) {
        let params = {
          'status': -1,
          'tag_ids': row.tag_id.toString()
        }
        this.$confirm('确认要删除该标签吗？')
          .then(_ => {
            API_goodsTag.deleteTag(params).then(response => {
              this.$message.success("操作成功");
              this.GET_TagsList();
            }).catch((error) => {
              console.log(error)
            })
          })
          .catch(_ => {});
      },
      /** 搜索事件触发 */
      searchEvent(data) {
        this.params = {
          ...this.params,
          tag_name: data
        };
        this.params.page_no = 1;
        this.GET_TagsList();
      },
      /**
       * @date 2020/09/23
       * @author kaiqiang
       * @description { 高级搜索事件 }
       */
      advancedSearchEvent() {
        let form = this.advancedForm.goods_tag_display_position
        if (form.length) {
          for (let i = 0; i < form.length; i++) {
            if (form[i] === 0) {
              this.advancedForm.goods_list_page = 0;
            } else if (form[i] === 1) {
              this.advancedForm.goods_details_page = 0;
            } else if (form[i] === 2) {
              this.advancedForm.shop_home_page = 0;
            }
          }
        }
        if (!this.advancedForm.times_range) {
          this.advancedForm.times_range = [];
          this.advancedForm.start_time = undefined;
          this.advancedForm.end_time = undefined;
        }
        if (this.advancedForm.times_range.length > 0) {
          this.advancedForm.start_time = this.advancedForm.times_range[0].getTime() / 1000;
          this.advancedForm.end_time = this.advancedForm.times_range[1].getTime() / 1000;
        }
        this.params = {
          ...this.params,
          ...this.advancedForm
        }
        this.params.page_no = 1;
        this.GET_TagsList();
        form =  [];
        this.advancedForm.shop_home_page = undefined;
        this.advancedForm.goods_list_page = undefined;
        this.advancedForm.goods_details_page = undefined
      },
      /**
        * @date 2020/11/30
        * @author kaiqiang
        * @description { 监听input框的输入长度 }
      */
      handleInputLength(value) {
        console.log(length.length)
        if (value.length > 6) {
          this.$message({
            type: 'error',
            message: '标签的名称不能超过6个字'
          })
          this.labelForm.tag_name = undefined
          return
        }
      }
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>
.wrapper {

    /deep/ div.toolbar {
      height: 70px;
      padding: 20px 0;
    }

    /deep/ .el-table {
      width: 100%;
      overflow-x: scroll;
      & td:not(.is-left) {
        text-align: center;
      }
    }

    .inner-toolbar {
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      width: 100%;
      justify-content: space-between;
      align-items: center;
    }

    /deep/ .pop-sku {
      .toolbar {
        display: none;
      }
      .el-dialog__body {
        .el-table {
          border: 1px solid #e5e5e5;
        }
      }
      .el-table__body-wrapper {
        max-height: 400px;
        overflow-y: scroll;
      }
    }

    .goods-image {
      width: 60px;
      height: 60px;
    }

    .goods-name {
      margin-left: 20px;
      top:50%;
      left: 50%;
      text-align: left;
    }

    .font-style {
      text-align: left;

      .font-color {
        color: red;
        font-size: 14px;
      }
    }

    .mytable {
      display: flex;
      color: #FD7F26;
      text-align: center;
      margin-top: 20px;
    }

    .footer {
      display: flex;
      justify-content: center;
    }
  }
  .el-input__inner {
    width: 100%;
  }
  .el-select {
    width: 100%;
  }
</style>
